<?php


/**
 * 联合登录项目
 */

namespace App\Http\Controllers\Union;

use App\Http\Controllers\Controller;
use App\Services\Alipay\AlipayUserService;
use App\Services\WeChat\WeChatUserService;
use Illuminate\Http\Request;


class InfoController extends Controller
{


    private $request;
    private $alipayUserService;
    private $weChatUserService;


    public function __construct(
        Request $request,
        AlipayUserService $alipayUserService,
        WeChatUserService $weChatUserService
    )
    {
        $this->request = $request;
        $this->alipayUserService = $alipayUserService;
        $this->weChatUserService = $weChatUserService;
    }


    private function factory($bindRef)
    {
        switch ($bindRef) {
            case 10:
            case 20:
                $obj = $this->weChatUserService;
                break;

            case 40:
            case 50:
                $obj = $this->alipayUserService;
                break;
            default :
                $obj = $this->weChatUserService;
                break;
        }

        return $obj;
    }


    /**
     * 拼接授权URL
     **
     *
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function authorizeUrl()
    {
        $bindRef = $this->request->get('bindRef');
        $scopes = $this->request->get('scopes');
        $callback = $this->request->get('callback');

        $config['bindRef'] = $bindRef;
        $obj = $this->factory($bindRef);

        $obj->setConfig($config);
        $result = $obj->authorizeUrl($scopes, $callback);

        return output(CODE_SUCCESS, 'success', $result);
    }

    /**
     * 通过code 获取授权信息
     **
     *
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function authorizeToken()
    {

        $bindRef = $this->request->post('bindRef');
        $code = $this->request->post('code');
        $extend = $this->request->post('extend', []);
        $obj = $this->factory($bindRef);
        $config['bindRef'] = $bindRef;
        $obj->setConfig($config);


        $result = $obj->authorizeToken($code, $extend);

        return output(CODE_SUCCESS, 'success', $result);
    }

    /**
     * 通过openID 和 accessToken 获取用户信息
     **
     *
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function authorizeUser()
    {

        $bindRef = $this->request->post('bindRef');
        $openID = $this->request->post('openID');
        $accessToken = $this->request->post('accessToken');

        $extend = $this->request->post('extend', []);

        $obj = $this->factory($bindRef);
        $config['bindRef'] = $bindRef;
        $obj->setConfig($config);


        $result = $obj->authorizeUser($openID, $accessToken);

        return output(CODE_SUCCESS, 'success', $result);
    }

}
